package com.cyclasoft.projects.ledom.configuration;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigurationUtil
{
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(ConfigurationUtil.class);

	public static File[] listDir(File f)
	{
		return f.listFiles(new FileFilter()
		{
			@Override
			public boolean accept(File pathname)
			{
				return pathname.isDirectory();
			}
		});
	}

	public static InputStream loadConfigFile(File dir, String defName, String altName)
	        throws LedomConfigurationException
	{
		logger.debug("search {}.cfg.xml in folder {}", defName, dir);
		File cfgFile = new File(dir, defName + ".cfg.xml");
		if (!cfgFile.exists())
		{
			logger.debug("search {}.cfg.xml in folder {}", altName, dir);
			cfgFile = new File(dir, altName + ".cfg.xml");
			if (!cfgFile.exists())
			{
				logger.debug("no config file found in {}", dir);
				return null;
			}
		}

		try
		{
			return new FileInputStream(cfgFile);
		}
		catch (FileNotFoundException e)
		{
			logger.error("open config file error", e);
			throw new LedomConfigurationException("file not found!", e);
		}
	}

}
